package com.qc31.monitorlib.ui.popup

import android.content.Context
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.PopupWindow
import com.qc31.baselib.rx.textChangesNoLong
import com.qc31.baselib.utils.toast
import com.qc31.comlib.databinding.IncludeNegativePositiveBinding
import com.qc31.monitorlib.R
import com.qc31.monitorlib.databinding.PopupMapSingleTimeBinding

/** @Author Jasper @Time 2020/10/29 @Desc 刷新时间 */
class SingleMapTimePopup(context: Context, private val callBack: OnTimeCallBack) : PopupWindow() {
    private val binding = PopupMapSingleTimeBinding.inflate(LayoutInflater.from(context))
    private val bindingNB = IncludeNegativePositiveBinding.bind(binding.root)

    init {
        contentView = binding.root

        bindingNB.tvNegative.setOnClickListener {
            val time = binding.editRefreshTime.text.toString()
            if (time.isEmpty()) {
                R.string.toast_sinle_refresh_time.toast(context)
                return@setOnClickListener
            } else if (time.toInt() < 3) {
                (context.getString(R.string.toast_sinle_refresh_time) + ":3~120").toast(context)
                return@setOnClickListener
            }
            callBack.onBack(time.toLong())
            dismiss()
        }

        bindingNB.tvPositive.setOnClickListener {
            dismiss()
        }

        binding.editRefreshTime.textChangesNoLong().subscribe {
            if (it.isNotEmpty()) {
                if (it.toInt() > 120) {
                    binding.editRefreshTime.setText("120")
                    binding.editRefreshTime.setSelection(binding.editRefreshTime.text.length)
                }
            }
        }

        isFocusable = true //popupwindow设置焦点
        setBackgroundDrawable(ColorDrawable(-0x56000000)) //设置背景
        isOutsideTouchable = false //点击外面窗口消失
        width = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的宽
        height = LinearLayout.LayoutParams.MATCH_PARENT //设置SelectPicPopupWindow弹出窗体的高
    }

    fun showPopupWindow(view: View, time: Long) {
        binding.editRefreshTime.setText(time.toString())
        binding.editRefreshTime.setSelection(binding.editRefreshTime.text.length)
        showAtLocation(view, Gravity.CENTER, 0, 0)
    }

    interface OnTimeCallBack {
        fun onBack(time: Long)
    }
}